<?php

namespace Index\Controller;

use Think\Controller;
use Index\ViewModel;
use Index\Service;

/**
 * 说明：礼物管理控制器
 * 作者：王楠
 * 创建日期：2017-09-15
 */
class GiftController extends CommonController
{

    public function giftlist()
    {
        $state_enum = getenumbykey('banner_state');
        $state_arr = getarrbyenum($state_enum);
        $app_code = $this->app_code;
        $state = trim(I('ddlstate'));
        $begintime = trim(I('txtbegintime'));
        $endtime = trim(I('txtendtime'));
        $keyword = trim(I('txtkeyword'));
        $appcode = trim(I('ddlapp'));

        if (!empty($app_code)) {
            $map['app_flag'] = $app_code;
        } else {
            if (!empty($appcode)) {
                $map['app_flag'] = $appcode;
            }
        }
        if (!empty($state)) {
            $map['state'] = $state;
        }
        if (!empty($begintime) || !empty($endtime)) {
            if (!empty($begintime) && !empty($endtime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
            } else if (!empty($begintime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
            } else if (!empty($endtime)) {
                $map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
            }
        }
        if (!empty($keyword)) {
            $where['chat_gift.id'] = array('eq', $keyword);
            $where['chat_gift.name'] = array('like', '%' . $keyword . '%');
            $where['chat_admin.username'] = array('like', '%' . $keyword . '%');
            $where['chat_admin.name'] = array('like', '%' . $keyword . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $viewModel = new ViewModel\GiftViewModel();
        $total = $viewModel->where($map)->count();
        $row = '10';
        $page = new Service\PageService($total, $row);
        $fpage = $page->fpage();
        $field = array(
            'id', 'name', 'icon', 'gold', 'price', 'state', 'username', 'admin_name', 'ctime'
        );
        $data = $viewModel->where($map)->limit($page->listfirst, $page->listRows)->field($field)->order('ctime desc')->select();
        foreach ($data as $key => $value) {
            $data[$key]['gold'] = (int)$data[$key]['gold'];
            $data[$key]['state_text'] = $state_enum[$data[$key]['state']];
            $data[$key]['admin_name'] = empty($data[$key]['admin_name']) ? $data[$key]['username'] : $data[$key]['admin_name'];
            $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
            $data[$key]['state_lab'] = $data[$key]['state'] == '1' ? '下架' : '上架';
            $data[$key]['state_class'] = $data[$key]['state'] == '1' ? 'btn-danger' : 'btn-info';
        }
        $search = array('appsel' => $appcode, 'statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
        $this->assign(array(
            'data' => $data,
            'fpage' => $fpage,
            'total' => $total,
            'statearr' => $state_arr,
            'search' => $search,
            'app_code' => $app_code,
            'apparr' => $this->getapplist()
        ));
        $this->display();
    }

    public function giftadd()
    {
        $id = I('id');
        $btnname = '添加';
        $columnname = '添加礼物';
        $state_enum = getenumbykey('gift_state');
        $state_arr = getarrbyenum($state_enum);
        if (!empty($id)) {
            $columnname = '修改礼物';
            $btnname = '修改';
            $viewModel = new ViewModel\GiftViewModel();
            $data = $viewModel->where(array('id' => $id))->find();
            $img = $data['icon'];
            $name = $data['name'];
            $gold = (int)$data['gold'];
            $price = $data['price'];
            $state = $data['state'];
            $admin_name = empty($data['admin_name']) ? $data['username'] : $data['admin_name'];
            $ctime = date('Y-m-d H:i', $data['ctime']);
        }
        foreach ($state_arr as $key => $value) {
            if ($state == $value['value']) {
                $state_arr[$key]['selected'] = "selected='selected'";
            }
        }
        $this->assign(array(
            'id' => $id,
            'img' => $img,
            'name' => $name,
            'gold' => $gold,
            'price' => $price,
            'state' => $state,
            'admin_name' => $admin_name,
            'ctime' => $ctime,
        ));
        $this->assign('columnname', $columnname);
        $this->assign('btnname', $btnname);
        $this->assign('statearr', $state_arr);
        $this->display();
    }

    public function giftaddsubmit()
    {
        if (!IS_POST) {
            $this->error('非法访问！');
        }
        $app_code = $this->app_code;
        $admin_id = $this->admin_id;
        $id = I('id');
        $img = trim(I('img'));
        $name = trim(I('name'));
        $gold = trim(I('gold'));
        $state = trim(I('state'));
        if (empty($img)) {
            $response = array('ret' => '1002', 'code' => '图片不能为空！');
            return $this->ajaxReturn($response, 'json');
        }
        if (empty($name)) {
            $response = array('ret' => '1002', 'code' => '名称不能为空！');
            return $this->ajaxReturn($response, 'json');
        }
        if (empty($gold)) {
            $gold = '0';
        }
        if (empty($state)) {
            $state = '1';
        }
        $systemModel = M('chat_systemset');
        $data_system = $systemModel->order('id desc')->find();
        $ratio = empty($data_system['ratio']) ? 0 : (int)$data_system['ratio'];
        $model = M('chat_gift');
        $gold = (int)$gold;
        $data['icon'] = $img;
        $data['name'] = $name;
        $data['gold'] = $gold;
        $data['price'] = $gold / $ratio;
        $data['state'] = $state;
        if (empty($id)) {
            $data['admin_id'] = $admin_id;
            $data['ctime'] = time();
            $data['app_flag'] = $app_code;
        }
        if (!empty($id)) {
            if ($model->where(array('id' => $id))->save($data)) {
                $response = array('ret' => '1001', 'code' => '修改成功！');
            } else {
                $response = array('ret' => '1001', 'code' => '修改成功！');
            }
        } else {
            if ($model->add($data)) {
                $response = array('ret' => '1001', 'code' => '添加成功！');
            } else {
                $response = array('ret' => '1002', 'code' => '添加失败！');
            }
        }
        return $this->ajaxReturn($response, 'json');
    }

    public function flagsubmit()
    {
        $id = I('id');
        if (!empty($id)) {
            $model = M('chat_gift');
            $data = $model->where(array('id' => $id))->find();
            if ($data) {
                $state = $data['state'];
                $lab = $state == '1' ? '下架' : '上架';
                $state = $state == '1' ? '2' : '1';
                $data['state'] = $state;
                $result = $model->save($data);
                if ($result) {
                    return $this->ajaxReturn(array('ret' => '1001', 'code' => $lab . '成功！', 'data' => $state));
                } else {
                    return $this->ajaxReturn(array('ret' => '1002', 'code' => $lab . '失败！', 'data' => $state));
                }
            } else {
                return $this->ajaxReturn(array('ret' => '1002', 'code' => '对不起，该幻灯片可能已被删除！'));
            }
        }
    }

    public function deletesubmit()
    {
        $id = I('id');
        if (!empty($id)) {
            $model = M('chat_gift');
            $result= $model->where(array('id' => $id))->delete();
            if ($result) {
                return $this->ajaxReturn(array('ret' => '1001', 'code' => '删除成功！'));
            } else {
                return $this->ajaxReturn(array('ret' => '1002', 'code' => '删除失败！'));
            }
        }
    }

    //上传图片
    public function imgupload()
    {
        $config = [
            'maxSize' => 1048576, // 设置附件上传大小
            'exts' => ['jpg', 'gif', 'png', 'jpeg'], // 设置附件上传类型
            'rootPath' => './Uploads/gift/', // 设置附件上传根目录
            'savePath' => '', // 设置附件上传（子）目录
            'autoSub' => false,
            'subName' => '',
            'saveName' => array('uniqid', ''),
        ];
        $rootPath = $config['rootPath'];
        if (!is_dir($rootPath)) {
            mkdir($rootPath);
        }
        $upload = new \Think\Upload($config); // 实例化上传类
        // 上传单个文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $error = $upload->getError();
            $data['ret'] = '1002';
            $data['code'] = $error;
            echo json_encode($data);
        } else {// 上传成功 获取上传文件信息
            $access_key_id = C('ACCESS_KEY_ID');
            $access_key_secret = C('ACCESS_KEY_SECRET');
            $img_url = C('IMG_URL');
            $img_url2 = C('IMG_URL2');
            $picName = $info['logoimg']['savename'];
            $picSize = $info['logoimg']['size'];
            $picTmp = $info['logoimg']['tmp_name'];
            $success = new \Vendor\OSS\OssClient($access_key_id, $access_key_secret, $img_url2);
            $ext = explode('.', $picName)[1];
            $picRemoteName = 'pc_gift_' . time() . rand(100000, 999999) . '.' . $ext;
            $bucket = C('BUCKET');
            $object = 'gift/' . $picRemoteName;
            $filePath = $rootPath . $picName;
            try {
                $success->uploadFile($bucket, $object, $filePath);
                unlink($rootPath . $picName);
                $img = $img_url . '/' . $object;
                $data['ret'] = '1001';
                $data['code'] = '上传成功！';
                $data['data'] = $img;
                echo json_encode($data);
            } catch (OssException $e) {
                $response = array('ret' => '1002', 'code' => '远程上传错误！');
                echo json_encode($data);
            }

//	    //返回本地路径
//	    $img = C('LOCALHOST_URL') . '/Uploads/gift/' . $info['logoimg']['savename'];
//	    $data['ret'] = '1001';
//	    $data['code'] = '上传成功！';
//	    $data['data'] = $img;
//	    echo json_encode($data);
        }
    }

}
